<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use App\Area;

class AreaController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct ()
    {
        //
    }

    /**
     * 根据已有的省市县三级分类json文件将省市信息写入数据库
     *
     * @return void
     */
    public function writeArea ()
    {
        $city = file_get_contents(__DIR__ . './city.txt');
        $city = str_replace(array(" ","　","\n","\r","\t"), array("","","","",""), $city);
        $content = json_decode($city, true);

        foreach ($content as $key => $value) {
            $firstAreaModel = new Area();
            $firstAreaModel->areaName = $value['name'];
            $firstAreaModel->type = 1;
            $firstAreaModel->parentID = 0;
            $firstAreaModel->save();

            $firstInsertId = $firstAreaModel->id;

            if (!empty($value['city'])) {
                foreach ($value['city'] as $k => $val) {
                    $secondAreaModel = new Area();
                    $secondAreaModel->areaName = $val['name'];
                    $secondAreaModel->type = 2;
                    $secondAreaModel->parentID = $firstInsertId;
                    $secondAreaModel->save();

                    $secondInsertId = $secondAreaModel->id;

                    if (!empty($val['area'])) {
                        foreach ($val['area'] as $areaKey => $areaVal) {
                            $thirdAreaModel = new Area();
                            $thirdAreaModel->areaName = $areaVal;
                            $thirdAreaModel->type = 3;
                            $thirdAreaModel->parentID = $secondInsertId;
                            $thirdAreaModel->save();
                        }
                    }
                }
                
            }
        }


        return ['status' => 0];
    }

    /**
     * 获取区域三级分类接口
     * 
     * return 
     * status: 0 成功 1 失败
     * data: 具体车系下的所有车型数据数组
     *
     * @return void
     */
    public function getArea ()
    {
    }
}
